package com.handpay.zztong.hp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.MD5;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.FunctionInfo;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.BitmapUtil;
import com.xys.libzxing.zxing.encoding.EncodingUtils;


public class ScannerCodePayActivity extends ZZTongActivity implements OnClickListener {
    private Button save_btn;
    private ImageView qrcode_iv;
    private Bitmap mQRCodeBitmap;
    private RelativeLayout capture_screen_ll;
    private FrameLayout body_fl;
    public static final String ShowHtml_Html_Path_Key = "ShowHtml_Html_Path_Key";
    public static final String Action_Key = "Action_Key";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.layout_scanner_code_pay);
        super.onCreate(savedInstanceState);
        qrcode_iv = (ImageView) this.findViewById(R.id.qrcode_iv);
        save_btn = (Button) this.findViewById(R.id.save_btn);
        capture_screen_ll = (RelativeLayout) this.findViewById(R.id.capture_screen_ll);
        body_fl = (FrameLayout) this.findViewById(R.id.body_fl);
        save_btn.setOnClickListener(this);
        BitmapDrawable ic_launcher = (BitmapDrawable) this.getResources().getDrawable(R.drawable.ic_launcher);
        String host = getIntent().getStringExtra(ShowHtml_Html_Path_Key);
        String action = getIntent().getStringExtra(Action_Key);
        String url;
        String merchantCode = AccountUtils.getMerchantCode(this);
        String secretkey = "HaN_yIn_scan_Pay";
        String sign = new MD5().getMD5ofStr(merchantCode + secretkey).toLowerCase();

        if (action.equals(FunctionInfo.QR_CODE_CODE)){
            myActionBar.setTitleText("码上付");
            url = host + "?channel=" + ClientEngine.CHANNEL + "&merchantCode=" + merchantCode;
        }else{
            url = host + "?channel=" + ClientEngine.CHANNEL + "&merchantCode=" + merchantCode + "&clientChannel=" + ZZTConfig.UPDATE_CHANNEL + "&clientVersion=v" + ClientEngine.VERSION + "&sign=" + sign;
        }

        HPLog.i(HPLog.YL_TAG, "load url:" + url);

        mQRCodeBitmap = EncodingUtils.createQRCode(url, CommonUtils.dp2px(280), CommonUtils.dp2px(280), ic_launcher.getBitmap());
        qrcode_iv.setImageBitmap(mQRCodeBitmap);
        this.findViewById(R.id.tv_hint_scanqrcode).setVisibility(View.VISIBLE);
        this.findViewById(R.id.tv_foot_hint).setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.save_btn) {
            doSaveBtn();
        } else if (v.getId() == R.id.scanner_code_pay_weixin_btn) {
            doWeChatScan();
        } else if (v.getId() == R.id.scanner_code_pay_alipay_btn) {
            doAlipayScan();
        }
    }

    private void doAlipayScan() {
        try {
            if (CommonUtils.isAlipayClientAvailable(this)) {
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.eg.android.AlipayGphone");
                startActivity(intent);
            } else {
                Toast.makeText(this, "无法跳转到支付宝，请检查您是否安装了支付宝！", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            //若无法正常跳转，在此进行错误处理
            Toast.makeText(this, "无法跳转到微信，请检查您是否安装了微信！", Toast.LENGTH_SHORT).show();
        }
    }

    private void doWeChatScan() {
        try {
            if (CommonUtils.isWeixinClientAvailable(this)) {
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                startActivity(intent);
            } else {
                Toast.makeText(this, "无法跳转到微信，请检查您是否安装了微信！", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            //若无法正常跳转，在此进行错误处理
            Toast.makeText(this, "无法跳转到微信，请检查您是否安装了微信！", Toast.LENGTH_SHORT).show();
        }
    }


    void doSaveBtn() {
        body_fl.setDrawingCacheEnabled(true);
        body_fl.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(body_fl.getDrawingCache());
        body_fl.setDrawingCacheEnabled(false);
        if (bitmap != null) {
            new SaveImageTask().execute(bitmap);
        }


//        if (mQRCodeBitmap != null) {
//            new SaveImageTask().execute(mQRCodeBitmap);
//        }else {
//            Toast.makeText(this, "不能保存空的二维码！", Toast.LENGTH_SHORT).show();
//        }
    }

    private void doShowDialog() {
        ZZTShowDialog mShowMarketDialog = new ZZTShowDialog(this, R.layout.dialog_scanner_code_pay, R.style.DialogSlideAnim);
        Window window = mShowMarketDialog.getDialog().getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = screenWidth;
        window.setAttributes(lp);
        mShowMarketDialog.getDialog().findViewById(R.id.scanner_code_pay_weixin_btn).setOnClickListener(this);
        mShowMarketDialog.getDialog().findViewById(R.id.scanner_code_pay_alipay_btn).setOnClickListener(this);
        mShowMarketDialog.setDialogCallback(new ZZTShowDialog.Dialogcallback() {
            @Override
            public void ButtonOk() {

            }

            @Override
            public void ButtonCancel() {

            }
        });
        mShowMarketDialog.show();
    }


    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.scanner_code_pay), true);
    }


    /***
     * 异步保存二维码图片
     */
    private class SaveImageTask extends AsyncTask<Bitmap, Void, String> {
        @Override
        protected String doInBackground(Bitmap... params) {
            byte[] bitmap2Bytes = BitmapUtil.Bitmap2Bytes(params[0]);
            if (bitmap2Bytes.length > 0) {
            }
            String path = BitmapUtil.saveByte_File(bitmap2Bytes, "qrcode", ScannerCodePayActivity.this);
            return path;
        }

        @Override
        protected void onPostExecute(String path) {
            if (!TextUtils.isEmpty(path)) {
                Toast.makeText(ScannerCodePayActivity.this, getResources().getString(R.string.save_pic_success), Toast.LENGTH_SHORT).show();
                doShowDialog();
            } else {
                Toast.makeText(ScannerCodePayActivity.this, getResources().getString(R.string.save_pic_fail), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        HPLog.i(HPLog.TAG_RESULT, "---onSaveInstanceState---");
        AccountUtils.Account account = ((ZZTApplication) this.getApplicationContext()).getAccount();
        HPLog.i(HPLog.TAG_RESULT, "username:" + AccountUtils.getAccountName(this));
        outState.putSerializable(key_saveInstanceState, account);
    }


}
